package com.zrx.handler.security;

import com.alibaba.fastjson.JSON;
import com.zrx.domain.ResponseResult;
import com.zrx.enums.AppHttpCodeEnum;
import com.zrx.utils.WebUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证异常
 * @author 张荣欣
 * @create ：2022/9/19  10:35
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {



    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException {

        authenticationException.printStackTrace();
         ResponseResult result = null;
        //相应给前端
//        InsufficientAuthenticationException  没有token 需要登录
//        BadCredentialsException   账号密码错误
        if (authenticationException instanceof BadCredentialsException){
            result = ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR.getCode(),authenticationException.getMessage());
        }else if(authenticationException instanceof InsufficientAuthenticationException){
            result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }else {
            result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(),"认证或授权失败");
        }

        WebUtils.renderString(response, JSON.toJSONString(result));
    }
}
